<?php

namespace app\utils\scrapy;

use app\index\model\Configuration;
use app\shop_admin\service\CommodityService;
use app\shop_admin\service\PicService;
use GuzzleHttp\Client;
use think\App;
use think\facade\Cache;
use think\facade\Db;

class Base
{
    public $oss_url = '';
    public $mall_id = 0;
    public $url = '';
    public $param = [];
    public $data;
    public $apikey = '';
    public $apiUrl = '';
    public $success_data=[];

    public function __construct($url = '')
    {

        global $user;
        $picService = new PicService();
        list($code, $msg) = $picService->getUrl();
        $this->oss_url = $msg;
        $this->mall_id = $user->mall_id;
        $this->url = $url;

        $this->getId($url);

        $config = Db::table('jiecheng_configuration')
            ->where('type', 'scrapy')
            ->where('mall_id', $user->mall_id)
            ->value('configuration');
        $config = json_decode($config, true);

        $this->apikey = $config['apikey'] ?? '';

        if (empty($this->param)) {
            throw new \Exception("url异常" . $this->url, HTTP_NOLICENSE);
        }
    }

    #兼容所有平台
    public function getId($url = "")
    {

        $parse_info = parse_url($url);
        $path = $parse_info['path'];
        if (self::getType($url) == "Suning") {
            preg_match("&(\d+)/(\d+).html&", $path, $data);
            if(empty($data[2])){
                throw new \Exception("苏宁链接异常" , HTTP_NOLICENSE);
            }
            $param['shopid'] = $data[1];
            $param['itemid'] = $data[2];
            $this->param = $param;
        } else {
            preg_match("&(\d+).html&", $path, $data);
            if (!empty($data[1])) {
                $param['itemid'] = $data[1];
            } else {
                if (isset($parse_info['query'])) {
                    parse_str($parse_info['query'], $query);
                    if (isset($query['id'])) {
                        $param['itemid'] = $query['id'];
                    } elseif (isset($query['goods_id'])) {
                        $param['itemid'] = $query['goods_id'];
                    } elseif (isset($query['object_id'])) {
                        $param['itemid'] = $query['object_id'];
                    }
                }
            }
            $this->param = $param;
        }



    }

    public static function getType($url)
    {


        if (mb_strpos($url, "jd.com")) {
            return "Jd";
        } elseif (mb_strpos($url, "pinduoduo.com")) {
            return "Pdd";
        } elseif (mb_strpos($url, "suning.com")) {
            return "Suning";
        } elseif (mb_strpos($url, "taobao.com")) {
            return "Taobao";
        } elseif (mb_strpos($url, "1688.com")) {
            return "Taobao1688";
        } elseif (mb_strpos($url, "detail.tmall.com")) {
            return "Tmall";
        }
        return false;

    }

    #固定数据
    public function common_data()
    {
        $post = \request()->post();
        $classify_id = $post['classify_id'] ?? '';
        $classify_value = $post['classify_value'] ?? '';
        $common_data = [
            'classify_id' => $classify_id,#'12,12->23,12->24,12->25,12->26,12->27',
            'classify_value' => $classify_value,#'热销爆款 ,当季热销,当季热销,当季热销,当季热销,当季热销',
            'attach_value' => [],
            'create_time' => date("Y-m-d H:i:s"),
            'deliver' => '1',
            'distribution' => [],
            'form_open' => 0,
            'fraction' => 0,
            'ft_id' => 0,
            'ft_price' => 0,
            'ft_type' => 0,
            'integral' => 0,
            'integral_deduction' => 0,
            'integral_maximum' => 0,
            'inventory_type' => 3,
            'is_base_distribution' => 0,
            'is_distribution' => 0,
            'is_integral' => 1,
            'is_intra_city' => 0,
            'is_limitation' => 0,
            'is_open_member_price' => 0,
            'is_original_price' => 0,
            'is_store_inventory' => 0,
            'is_virtual' => 1,
            'label' => ['正品保证', '假一赔十', '七天无理由退货'],
            'level_price' => [
                'price' => [['level' => 1, 'price' => 0, 'type' => 1], ['level' => 2, 'price' => 0, 'type' => 1], ['level' => 3, 'price' => 0, 'type' => 1]],
                'type' => 1
            ],
            'limitation' => '',
            'limitation_time' => date("Y-m-d H:i:s"),
            'limitation_type' => 1,
            'member_price' => null,
            'member_price_type' => 1,
            'merchant_id' => 1,
            'retreat' => '1,2,3',
            'sell' => 0,
            'sort' => 0,
            'type' => 0,
            'virtual_sell' => 0,
            'share' => '',
            'parameter' => [],
            'template_id' => 0,
            'weight' => 0,

        ];

        return $common_data;
    }

    #写入数据库
    public function write($data)
    {
        $data = array_merge($data, $this->common_data());
        $service = new CommodityService();

        $service->save($data);
        $this->success_data=$data;
    }
    public function getSuccessData(){
        return $this->success_data;
    }

    public function getData()
    {
        $param = http_build_query($this->param);
        $api = "https://api09.99api.com{$this->apiUrl}?apikey={$this->apikey}&$param";

        $key = "scrapy_urls:" . $api;
        $data = Cache::get($key);
        if (empty($data)) {
            $client = new Client();
            $response = $client->request("get", $api);
            $content = $response->getBody()->getContents();
            $data = json_decode($content, true);
            if ($data['retcode'] != "0000") {
                $errmsg=is_string($data['data']) ? $data['data'] : '';
                throw new \Exception("数据异常" . $this->url . "状态码:" . $data['retcode'] . "错误信息:".$errmsg, HTTP_NOLICENSE);
            }
            Cache::set($key, $content, 7 * 24 * 60 * 60);
        } else {
            $data = json_decode($data, true);
        }
        $this->data = $data;
        return $data;
    }
    public function writeLog(){
        LiveLog::write(
            '重新审核商品',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播商品id' => $model->id,
                    '商品id' => $model->goods_id,
                ]
            ]
        );
    }
}